#!/usr/bin/env bash

# Make sure root can't run this script
if [ "$(id -u)" == "0" ]; then
   echo "You can't run this script as root" 1>&2
   exit 1
fi
      

### Loading tunnel's configuration ###
if [ "$1" -a -f "$1" ]; then 
    source $1
else
    # NO configuration file found ... dump error and exit
    echo "OUPS! No configuration file path specified as first argument"
    exit
fi


### Function : Starting tunnel ###
starting_tunnel(){
    # Starting remote tunnel
    echo "Starting SSHMeIn's remote tunnel on $user@$listening_host port $listening_port"
    $SSH_BINARY -f -N -R "$listening_port":localhost:"$LOCAL_SSHD_PORT" "$user"@"$listening_host" 2>/dev/null
    
    # Logging tunnel's pid for kill command
    pid="`ps auxw | grep $listening_host | grep -v grep | awk '{print $2}'`"
    
    # Does tunnel started ?
    if [ "$pid" ]; then
        echo $pid > $PID_FILE
        echo "SSHMeIn's tunnel started as pid $pid"
    else
        echo "OUPS! Can't start SSHMeIn's tunnel"
    fi
}


### Function : Killing all running tunnel ###
kill_all_tunnel(){
    pids=$(cat $PID_FILE 2>/dev/null);
    for p in $pids
        do echo "Stopping SSHMeIn's tunnel pid $p ..."; kill $p 2>/dev/null
    done;    
}



### Command for checking remote tunnel service ###
if [ "$SERVICE_TYPE" == 'PRETTYURL' ]; then
    command="$CURL_BINARY -s -w :%{http_code} $SERVICE_URL$TUNNEL_KEY"
else
    command="$CURL_BINARY -s -w :%{http_code} $SERVICE_URL?key=$TUNNEL_KEY"
fi

### Calling service to obtain tunnel's status ###
echo "Calling remote tunnel service with $command"
data=$($command)                                                                                                                   

### Temporarily overwriting Internal Field Separator ###                                                                                                                                          
OLD_IFS="$IFS"                                                                                                                                    
IFS=":"                                                                                                                                           
          
### Settings Array with tunnel's parameters          
tunnelParams=($data)                                                                                                                                      
                                           
### Back to default IFS ###                                           
IFS="$OLD_IFS"                    

### Count elements in array of parameters ###
tunnelParamsLength=${#tunnelParams[@]}             

### Get HTTP status code from Curl call ###
httpStatusCode=${tunnelParams[$tunnelParamsLength - 1]}                                                                                                                              
                
### Check mandatory HTTP status code and required parameters ###
if [ "$httpStatusCode" == 200 ] && [ "$tunnelParamsLength" == 4 ]; then
    ### Tunnel requested so ...
    echo "Requested tunnel state : ON"
        
    # Which user to use for establish tunnel connection
    user=${tunnelParams[0]}

    # Which ssh server to connect tunnel on
    listening_host=${tunnelParams[1]}

    # Which ssh port to connect tunnel on 
    listening_port=${tunnelParams[2]}
	
    if [ ! -f $PID_FILE ]; then
        # No PID file, no active tunnel... 
        # Enabling tunnel as requested
        starting_tunnel
    else
        #PID file exists, check if a stalled tunnel
	echo "Checking if the tunnel still exist"
	current_PID=$(cat $PID_FILE 2>/dev/null);
	if [[ $(ps auxw | grep "$current_PID" | grep "ssh" | grep "localhost" | grep -q 1 )$? == 0 ]]; then
	  echo "Tunnel still exist, nothing to do!"
	else
	  echo "Tunnel is dead! Removing PID file and starting new tunnel instance"
	  rm -f $PID_FILE
	  starting_tunnel
	fi
	
    fi
else
    # NO tunnel requested or bad curl call to web services
    # killing the last tunnel if still running...
    echo "Requested tunnel state : OFF"
    if [ -f $PID_FILE ]; then
        echo "Closing current active tunnel"
        kill_all_tunnel
        rm -f $PID_FILE
    else
        echo "No active tunnel ...nothing to do"
    fi
fi
